#include "Arduino.h"
#include "ESP.h"
/** ESP8266 设置**/
#define MAX_PACKETSIZE 64
const char *join = "AT+CWJAP=\"MERCURY_B19736\",\"18423579228\"";
SoftwareSerial softSerial(RX, TX); // RX -- 10, TX --- 11

/*接入OneNET平台设置*/
const uint32_t deviceID = 31467655;
const char *Apikey = "api-key:ZSEo2zShjzxe=sXOSBOUJB8STq8=";
const char *Host = "Host:api.heclouds.com";

/** ESP8266 初始化设置 **/
int ESPINIT::init(void)
{
  softSerial.begin(115200);
  while(!softSerial){;};
  softSerial.println("+++");
  Serial.print("INIT ESP8266 SETTING , WAIT...!");
  softSerial.println("ATE0");
  softSerial.println("AT+CWMODE=1");
  delay(1000);  
  this->msg();    // 读取传入的数据:
  softSerial.println(join);
  delay(5000);
  this->msg();    // 读取传入的数据:
  if(softSerial.find("ok")){
      Serial.println("#ESP Connect wifi sucessfull !");
  }
  
  softSerial.println("AT+CIFSR");
  delay(5000);
  this->msg();
  Serial.println("#设置初始化 ESP 成功 !");
}

/** ESP8266 设置信息显示 **/
void ESPINIT::msg()
{
  static uint8_t buffsoftSerial[MAX_PACKETSIZE];
  static unsigned int buffsoftSerialIndex = 0;
  static unsigned long presoftSerialTime = millis();
  uint8_t t = 0;

while (softSerial.available() > 0) {
    t = softSerial.read();
    buffsoftSerial[buffsoftSerialIndex++] = t ;
    presoftSerialTime = millis();
    if (buffsoftSerialIndex >= MAX_PACKETSIZE - 1) {
      buffsoftSerialIndex = MAX_PACKETSIZE - 2;
      presoftSerialTime = presoftSerialTime - 100;
    }

    if (buffsoftSerialIndex > 0 && (millis() - presoftSerialTime >= 50 || t == '\n'))
    { 
      buffsoftSerial[buffsoftSerialIndex] = 0x00;
      softSerial.flush();
      Serial.write(buffsoftSerial, buffsoftSerialIndex);
      buffsoftSerialIndex = 0;
    }
  }
}

/** ONENET 平台连接 采用 HTTP 协议 **/
int ESPINIT::connect()
{
  softSerial.println("AT+CIPSTART=\"TCP\",\"183.230.40.33\",80");
  delay(1500);
  softSerial.println("AT+CIPMODE=1");
  delay(1500);
  softSerial.println("AT+CIPSEND");
  delay(1000);
  return 0;
}

/** 上传数据到ONENET中**/
void ESPINIT::send(int jsonLen,String jsonMsg)
{
   Serial.println("Send POST");
   softSerial.println("POST /devices/31467655/datapoints?type=3 HTTP/1.1");
   softSerial.println(Apikey);
   softSerial.println(Host);
   softSerial.println("Connection:close");
   softSerial.print("Content-Length:"); 
   softSerial.println(jsonLen);
   softSerial.println();
   softSerial.println(jsonMsg);
   softSerial.println("+++");
}

/**制造重启命令 函数指针**/
void (* resetFunc) (void) = 0;

/**软重启**/
void ESPINIT::reset(void)
{
  Serial.println("# soft reset system");
  delay(500);
  resetFunc();
}
